import 'dart:async';

import 'api.dart';

class Request {
  final String _api;
  final Map<String, dynamic> _param;
  var tryTimes = 0;
  var maxTimes = 10;

  var errorTimes = 0;

  Map<String, dynamic>? data;
  Completer<Map<String, dynamic>>? dataCompleter;
  bool isLoading = false;

  Request(this._api, [this._param = const {}]);

  void setParam(String key, Object val) {
    _param[key] = val;
    data = null;
    if (dataCompleter != null) {
      if (!dataCompleter!.isCompleted) {
        dataCompleter!.future.then((value) => dataCompleter = null);
      }
    }
  }

  Object getParam(String key) {
    return _param[key];
  }

  Future<Map<String, dynamic>> getData({bool force = false}) async {
    if (data == null || force) {
      if (dataCompleter != null && !dataCompleter!.isCompleted) {
        return await dataCompleter!.future;
      }
      dataCompleter = Completer();
      data = await _request();
      dataCompleter!.complete(data!);
    }
    return data!;
  }

  Future<Map<String, dynamic>?> _request() async {
    if (isLoading) throw Exception('Frequent requests!');
    isLoading = true;
    var result = await Api.post(_api, _param);
    isLoading = false;
    if(result.statusCode != 200 || result.code != 1){
      dataCompleter?.completeError(Exception(result.message));
      throw ServerException.fromResult(result);
    }
    return result.data;
  }
}
